package lol.oxguy3.droidcalc;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import android.widget.TableRow.LayoutParams;

public class CalcActivity extends Activity /*implements View.OnClickListener*/ {
	
	TextView outputview;
	int currentfunc; //negative=showing answer, 0=none, 1=add, 2=subtract, 3=multiply, 4=divide, 5=power, 6=root
	double firstnumber;
	//double currentnum;
	boolean pressedEquals;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        outputview = new TextView(this);
        outputview.setText("");
        outputview.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        
        Button btnkey1 = new Button(this);
        Button btnkey2 = new Button(this);
        Button btnkey3 = new Button(this);
        Button btnkey4 = new Button(this);
        Button btnkey5 = new Button(this);
        Button btnkey6 = new Button(this);
        Button btnkey7 = new Button(this);
        Button btnkey8 = new Button(this);
        Button btnkey9 = new Button(this);
        Button btnkey0 = new Button(this);
        Button btnkeydot = new Button(this);
        Button btnkeyneg = new Button(this);
        Button btnkeyclr = new Button(this);
        Button btnkeyadd = new Button(this);
        Button btnkeysubt = new Button(this);
        Button btnkeymult = new Button(this);
        Button btnkeydiv = new Button(this);
        Button btnkeypwr = new Button(this);
        Button btnkeyroot = new Button(this);
        Button btnkeyeq = new Button(this);
        
        Button[] btnkeys_num = {btnkey1,btnkey2,btnkey3,btnkey4,btnkey5,btnkey6,btnkey7,btnkey8,btnkey9,btnkey0};
        Button[] btnkeys_func = {btnkeydot,btnkeyneg,btnkeyclr,btnkeyadd,btnkeysubt,btnkeymult,btnkeydiv,btnkeypwr,btnkeyroot,btnkeyeq};
        
        
        btnkey1.setText("1");
        btnkey2.setText("2");
        btnkey3.setText("3");
        btnkey4.setText("4");
        btnkey5.setText("5");
        btnkey6.setText("6");
        btnkey7.setText("7");
        btnkey8.setText("8");
        btnkey9.setText("9");
        btnkey0.setText("0");
        btnkeydot.setText(".");
        btnkeyneg.setText("\u00B1");
        btnkeyclr.setText("C");
        btnkeyadd.setText("\u002B");
        btnkeysubt.setText("\u2212");
        btnkeymult.setText("\u00D7");
        btnkeydiv.setText("\u00F7");
        btnkeypwr.setText("^");
        btnkeyroot.setText("\u207F\u221A");
        btnkeyeq.setText("=");
        
        
        
        int numpadbgcolor = 0xFFBBBBBB;
        int funckeybgcolor = 0xFFAA0000;
        
        
        OnClickListener btnkeyOnClickListener = new OnClickListener() {
        	public void onClick(View v) {
        		Button btn = (Button)v;
        		
				String buttonname = (String)btn.getText();
				onButtonClick(buttonname);
			}
        };
        
        
        for(int i = 0; i<btnkeys_num.length; i++) {
        	btnkeys_num[i].setBackgroundColor(numpadbgcolor);
        	btnkeys_num[i].setOnClickListener(btnkeyOnClickListener);
        }
        
        for(int i = 0; i<btnkeys_func.length; i++) {
        	btnkeys_func[i].setBackgroundColor(funckeybgcolor);
        	btnkeys_func[i].setOnClickListener(btnkeyOnClickListener);
        }
        
        
        TableLayout numpadLayout = new TableLayout(this);//(TableLayout) findViewById(R.id.mainLayout);
        numpadLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        numpadLayout.setStretchAllColumns(true);
        
        TableRow numpadRow1 = new TableRow(this);
        numpadRow1.addView(btnkey7, new TableRow.LayoutParams(0));
        numpadRow1.addView(btnkey8, new TableRow.LayoutParams(1));
        numpadRow1.addView(btnkey9, new TableRow.LayoutParams(2));
        numpadRow1.addView(btnkeyadd, new TableRow.LayoutParams(3));
        
        TableRow numpadRow2 = new TableRow(this);
        numpadRow2.addView(btnkey4, new TableRow.LayoutParams(0));
        numpadRow2.addView(btnkey5, new TableRow.LayoutParams(1));
        numpadRow2.addView(btnkey6, new TableRow.LayoutParams(2));
        numpadRow2.addView(btnkeysubt, new TableRow.LayoutParams(3));
        
        TableRow numpadRow3 = new TableRow(this);
        numpadRow3.addView(btnkey1, new TableRow.LayoutParams(0));
        numpadRow3.addView(btnkey2, new TableRow.LayoutParams(1));
        numpadRow3.addView(btnkey3, new TableRow.LayoutParams(2));
        numpadRow3.addView(btnkeymult, new TableRow.LayoutParams(3));
        
        TableRow numpadRow4 = new TableRow(this);
        numpadRow4.addView(btnkeydot, new TableRow.LayoutParams(0));
        numpadRow4.addView(btnkey0, new TableRow.LayoutParams(1));
        numpadRow4.addView(btnkeyneg, new TableRow.LayoutParams(2));
        numpadRow4.addView(btnkeydiv, new TableRow.LayoutParams(3));
        
        TableRow numpadRow5 = new TableRow(this);
        numpadRow5.addView(btnkeyeq, new TableRow.LayoutParams(0));
        numpadRow5.addView(btnkeyclr, new TableRow.LayoutParams(1));
        numpadRow5.addView(btnkeypwr, new TableRow.LayoutParams(2));
        numpadRow5.addView(btnkeyroot, new TableRow.LayoutParams(3));
        
        TableLayout.LayoutParams numpadTableParams = new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        
        numpadLayout.addView(outputview, numpadTableParams);
        numpadLayout.addView(numpadRow1, numpadTableParams);
        numpadLayout.addView(numpadRow2, numpadTableParams);
        numpadLayout.addView(numpadRow3, numpadTableParams);
        numpadLayout.addView(numpadRow4, numpadTableParams);
        numpadLayout.addView(numpadRow5, numpadTableParams);
        
        
        LinearLayout mainLayout = (LinearLayout) findViewById(R.id.mainLayout);
        mainLayout.addView(numpadLayout);
        
        currentfunc = 0;
        pressedEquals = false;
    }
    
    public void pressedFuncKey() {
    	System.out.println(String.valueOf(firstnumber));
    	if (firstnumber==0){
    		System.out.println("New equation!");
    		
	    	if (((String)outputview.getText()).equals("")) { //don't allow the user to perform math without inputting numbers
	    		outputview.setText("0");
	    	}
	    	firstnumber = Double.parseDouble((String)outputview.getText()); //currentnum;
	    	outputview.setText(""); //currentnum = 0;
	    	
    	} else {
    		double answer = equatify(firstnumber, Double.parseDouble((String)outputview.getText()), Math.abs(currentfunc));
    		firstnumber = answer;
    		outputview.setText(Double.toString(answer));
    		
    	}
    }
    public void setCurrentfunc(int func) {
    	int multiplier = 1;
		if (currentfunc<0) {
			multiplier = -1;
		}
		currentfunc = func * multiplier;
    }
    
    public void onButtonClick(String btnname) {
    	
    	if (btnname.equals(".")) { //decimal
    		clearOutSolution();
    		if (((String) outputview.getText()).indexOf(".")==-1){
	    		outputview.setText(outputview.getText()+btnname);
	    		handleNumpadClick();
    		}
    		
    	} else if (btnname.equals("\u00B1")) { //toggle negative
    		
    		if (((String)outputview.getText()).startsWith("-")) {
    			outputview.setText(((String)outputview.getText()).substring(1));
    		} else {
    			if (!((String)outputview.getText()).equals("")) {
        			outputview.setText("-"+((String)outputview.getText()));
    			}
    		}
    		/*if (currentnum!=0) {
    			currentnum*=-1;
    		}*/
    		
    	} else if (btnname.equals("C")) { //clear
    		outputview.setText("");
    		firstnumber=0;
    		currentfunc=0;
    		
    	} else if (btnname.equals("=")) { //equate
    		double answer = equatify(firstnumber, Double.parseDouble((String)outputview.getText()), Math.abs(currentfunc));
    		outputview.setText(Double.toString(answer));
    		
    	} else if (btnname.equals("\u002B")) { //add
    		pressedFuncKey();
    		setCurrentfunc(1);
    		
    	} else if (btnname.equals("\u2212")) { //subtract
    		pressedFuncKey();
    		setCurrentfunc(2);
    		
    	} else if (btnname.equals("\u00D7")) { //multiply
    		pressedFuncKey();
    		setCurrentfunc(3);
    		
    	} else if (btnname.equals("\u00F7")) { //divide
    		pressedFuncKey();
    		setCurrentfunc(4);
    		
    	} else if (btnname.equals("^")) { //power
    		pressedFuncKey();
    		setCurrentfunc(5);
    		
    	} else if (btnname.equals("\u207F\u221A")) { //root
    		pressedFuncKey();
    		setCurrentfunc(6);
    		
    	} else { //number
    		
    		//TODO: Need to deal with what happens if the user has hit a function key on the last button press
    		
    		clearOutSolution();
    		outputview.setText(outputview.getText()+btnname);
    		
    		//currentnum = Double.parseDouble(Double.toString(currentnum)+btnname);
    		//updateDisplay();
    		
    		handleNumpadClick();
    	}
    }
    
    /**
     * Clears out the solution to the last equation. To be called only if the user starts typing in a new number
     */
    public void clearOutSolution() {
    	
    	if (currentfunc<0) {
			firstnumber=Double.parseDouble((String)outputview.getText())/*0*/; //need to nullify this leftover from the past equation OR DO I?!?
    		outputview.setText("");
    		if (pressedEquals) {
    			currentfunc=0;
    		}
		}
    	pressedEquals = false;
    }
    
    public double equatify(double num1, double num2, int func) {
    	System.out.println("EQUATIFY: "+String.valueOf(num1)+", "+String.valueOf(num2)+", "+String.valueOf(func));
    	
    	double solution;
    	
    	if (func == 1) {
    		solution = num1 + num2;
    		
    	} else if (func == 2) {
    		solution = num1 - num2;
    		
    	} else if (func == 3) {
    		solution = num1 * num2;
    		
    	} else if (func == 4) {
    		solution = num1 / num2;
    		
    	} else if (func == 5) {
    		solution = Math.pow(num1, num2);
    		
    	} else if (func == 6) {
    		solution = Math.pow(num2, 1/num1); //TODO: Deal with negatives!
    		
    	} else {
    		solution = 0;
    	}
    	currentfunc = -1 * Math.abs(currentfunc);
    	System.out.println("equatify done! sol:"+solution+", currentfunc:"+currentfunc);
    	return solution;
    }
    
    /*public void updateDisplay() {
    	outputview.setText(Double.toString(currentnum));
    }*/
    
    /**
     * Cleans up the number formatting to remove extra zeroes from the front.
     * To be called after the user presses a number key or decimal key 
     */
    public void handleNumpadClick() {
    	String calc = (String)outputview.getText();
    	int decimalind = calc.indexOf(".");
    	
    	String beforedecimal, afterdecimal;
    	
    	if (decimalind != -1) {
    		beforedecimal = calc.substring(0, decimalind);
    		afterdecimal = calc.substring(decimalind);
    	} else {
    		beforedecimal = calc;
    		afterdecimal = "";
    	}
		
		while(beforedecimal.indexOf("0") == 0) {
			beforedecimal = beforedecimal.substring(1);
		}
		
		if (beforedecimal.equals("")) {
			beforedecimal="0";
		}
		
		calc = beforedecimal + afterdecimal;
		
		if (calc.startsWith(".")) {
			calc = "0" + calc;
		}
		
		outputview.setText(calc);
    }

	/*public void onClick(View v) {
		Button btn = (Button)v;
		
		String buttonname = (String)btn.getText();
		onButtonClick(buttonname);
	}*/
}